package com.socialvampic.language;

import java.util.Locale;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;

import com.socialvampic.mvc.model.AbstractModel;

public class Language extends AbstractModel {
	public static final String EN_KEY = "en";
	public static final String VI_KEY = "vi";
	public static final String LOCALE = "com.socialvampic.language.SharedPreferences";

	private Application mApplication;
	private SharedPreferences mPreferences;
	private String mLanguage;
	private Locale mLocale;
	private Configuration mConfiguration;

	/**
	 * Constructor
	 * 
	 * @param application
	 */
	public Language(Application application) {
		mApplication = application;
		mPreferences = mApplication.getApplicationContext()
				.getSharedPreferences(LOCALE, Activity.MODE_PRIVATE);
		String savedLanguage = mPreferences.getString(LOCALE, EN_KEY);
		switchLanguage(savedLanguage);
	}

	public void switchLanguage(String language) {
		// change language
		if (!language.equals(mLanguage)) {
			mLanguage = language;
			mLocale = new Locale(mLanguage);
			Locale.setDefault(mLocale);
			if (mConfiguration != null) {
				mConfiguration.locale = null;
			}
			mConfiguration = new Configuration();
			mConfiguration.locale = mLocale;
			// save SharedPreferences
			mPreferences.edit().putString(LOCALE, mLanguage).commit();
		}

		Context baseContext = mApplication.getBaseContext();
		Resources resources = baseContext.getResources();
		resources.updateConfiguration(mConfiguration,
				resources.getDisplayMetrics());

		notifyObservers();
	}

	public Application getApplication() {
		return mApplication;
	}

	public void setApplication(Application mApplication) {
		this.mApplication = mApplication;
	}

	public SharedPreferences getPreferences() {
		return mPreferences;
	}

	public void setPreferences(SharedPreferences mPreferences) {
		this.mPreferences = mPreferences;
	}

	public String getLanguage() {
		return mLanguage;
	}

	public Locale getLocale() {
		return mLocale;
	}

	public void setLocale(Locale mLocale) {
		this.mLocale = mLocale;
	}

	public Configuration getConfiguration() {
		return mConfiguration;
	}

	public void setConfiguration(Configuration mConfiguration) {
		this.mConfiguration = mConfiguration;
	}

}
